package com.zkw.group.controller;

import com.alibaba.fastjson.JSON;
import com.zkw.group.entity.QueryInfo;
import com.zkw.group.entity.User;
import com.zkw.group.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Api(description = "管理用户信息")
@CrossOrigin
@RestController
@RequestMapping("/Users")
public class UserController {

    @Autowired
    private UserService userService;


    @ApiOperation(value = "根据用户名和密码判断用户身份")
    @GetMapping("/Login")
    public String getRole(String username,String password){
        String flag = "n";
        String pid = userService.getRole(username,password);
        if(pid != null){
            if(pid.equals("管理员")){
                flag = "manager";
            }
            else if(pid.equals("课程负责人")){
                flag = "teacher";
            }
            else {
                flag = "professor";
            }
        }
        return flag;
    }


    @ApiOperation(value = "分页查询所有用户信息")
    @GetMapping("/selectAll")
    public String getUserList(QueryInfo queryInfo) {
        int numbers = userService.getUserCounts(queryInfo.getQuery());
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<User> users = userService.selectAll(queryInfo.getQuery(),pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",users);
        return JSON.toJSONString(res);
    }


    @ApiOperation(value = "添加新用户")
    @PostMapping("/User")
    public String insert(@RequestBody User user) {
        int result;
        try{
            result = userService.addUser(user);
        }
        catch(Exception e) {
            result = 0;
        }
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }


    @ApiOperation(value = "根据用户名查询用户信息")
    @GetMapping("/UserMessage")
    public String getUpdateUser(String username) {
        User updateUser = userService.getUpdateUser(username);
        String users_json = JSON.toJSONString(updateUser);
        System.out.println(users_json);
        return users_json;

    }


    @ApiOperation(value = "根据用户名更新用户信息")
    @PutMapping("/User")
    public String update(@RequestBody User user) {
        int result = userService.updateUser(user);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }


    @ApiOperation(value = "根据用户名删除用户信息")
    @DeleteMapping("/User")
    public String delete(String username) {
        int result = userService.deleteUser(username);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }

}
